<?php
declare(strict_types=1);


namespace App\Service;

use App\Model\User;

class UserService
{
    //用户redis key
    const USER_INFO= 'user_info';
    const FD_UID= 'fd_uid_';

    /**
     * 根据用户名获取用户
     * @param $username
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public static function getUserByUsername($username)
    {
        return User::where('username', $username)->first();
    }

    /*TODO *********************************************************游戏方法*******************************************************************↓↓↓↓↓*/

    /**
    * 初始化用户
    * @param $user
    */
    public static function initGameUser($user)
    {
        self::updateUserRedis($user['uid'], $user);
        //绑定fd,uid关系
        redis()->set(self::FD_UID.$user['fd'], $user['uid']);
    }

    /**
     * 根据FD获取用户信息
     * @param int $fd
     * @param null $server
     * @return array|null
     */
    public static function getUserByFd(int $fd, $server = null): ?array
    {
        if (!$server) {
            $server = websocket();
        }
        //获取客户端信息
        $client = $server->getClientInfo($fd);
        if ($client && isset($client['uid']) && !empty($client['uid'])) {
            return self::getUserRedis($client['uid']);
        }
        //缓存
        $uid = redis()->get(self::FD_UID.$fd);
        if ($uid) {
            return self::getUserRedis($uid);
        }
        return null;
    }

    /*TODO *********************************************************Redis数据*******************************************************************↓↓↓↓↓*/

    /**
     *
     * @param $uid
     * @return array | null
     */
    public static function getUserRedis($uid): ?array
    {
        return redis()->hGetAll(self::USER_INFO.$uid);
    }

    /**
     * 更新用户Redis信息
     * @param $uid
     * @param $data
     * @return bool
     */
    public static function updateUserRedis($uid, $data): bool
    {
        return redis()->hMSet(self::USER_INFO.$uid, $data);
    }

    /**
     * 移除Redis中用户数据
     * @param $uid
     * @return int
     */
    public static function removeUserRedis($uid): int
    {
        return redis()->del(self::USER_INFO.$uid);
    }
}